package cn.git.controller;

import cn.git.entity.Product;
import cn.git.socket.SocketUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.math.BigDecimal;
import java.net.Socket;

/**
 * @description: Socket测试controller
 * @program: bank-credit-sy
 * @author: lixuchun
 * @create: 2024-09-27
 */
@RestController
@RequestMapping("/socket")
public class SocketController {

    @GetMapping("/client")
    public String client() {
        for (int i = 0; i < 200; i++) {
            int finalI = i;
            new Thread(()-> {
                try {
                    // 创建Socket对象
                    Socket socket = new Socket("localhost", 7777);
                    // 设置超时时间
                    socket.setSoTimeout(60000);

                    // 测试产品
                    Product product = new Product();
                    product.setAmount(new BigDecimal(finalI));
                    product.setCycle(12);
                    product.setEndTime("2018-08-08");
                    product.setName("test");
                    product.setRate(new BigDecimal(1));
                    product.setRaised(new BigDecimal(0));

                    // 拼接请求报文
                    String message = JSONObject.toJSONString(product);
                    String reqLengthStr = SocketUtil.leftFixedZero(6, message.length());

                    // 使用utf-8编码发送请求报文
                    PrintStream out = new PrintStream(socket.getOutputStream());
                    out.println(reqLengthStr.concat(message));
                    // 获取服务端返回的消息长度信息
                    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    char[] lengthByte = new char[6];
                    in.read(lengthByte);
                    String rspLengthStr = new String(lengthByte);
                    int responseLength = Integer.parseInt(rspLengthStr);

                    // 获取服务端返回的消息体信息
                    char[] responseByte = new char[responseLength];
                    in.read(responseByte);
                    String responseBody = new String(responseByte);

                    // 打印返回结果
                    System.out.println("返回结果为 : ".concat(responseBody));
                    socket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }

        return "处理成功啦";
    }

}
